#include "CreditDebtRanking.h"
#include "CreditDebtRankingList.h"
#include "../StringResource.h"
#include "../FIDataCenter.h"
#include <core/StyleMgr.h>
#include <core/ImageMgr.h>
#include <QVBoxLayout>
#include <QStackedLayout>
#include <QMouseEvent>
#include <widgets/STabCtrl.h>

enum {
	emListActive = 0,	//活跃成交
	emListRankingUp,	//涨幅榜
	emListRankingDown,	//跌幅榜
	emList20DaysFirst	//20日首日异常成交
};

CreditDebtRanking::CreditDebtRanking(QWidget* p)
	: SDialog(p)
{
	setTitle(NewStringTable::strFixedIncomeTitle(2));

	QVBoxLayout* mainLayout = qobject_cast<QVBoxLayout*>(this->layout());
	if (!mainLayout)return;
	mainLayout->setContentsMargins(4, 0, 4, 4);

	m_tab = new STabCtrl(this);
	m_tab->addTab(NewStringTable::strFixedIncomeActiveTab(emListActive));
	m_tab->addTab(NewStringTable::strFixedIncomeActiveTab(emListRankingUp));
	m_tab->addTab(NewStringTable::strFixedIncomeActiveTab(emListRankingDown));
	m_tab->addTab(NewStringTable::strFixedIncomeActiveTab(emList20DaysFirst));
	m_tab->selectTab(0);
	m_tab->setFixedHeight(24);
	mainLayout->addWidget(m_tab);
	mainLayout->addSpacing(4);

	m_stackLayout = new QStackedLayout();
	for (int i=0; i<m_tab->getTabCount(); i++) {
		CreditDebtRankingList* list = CreateList(i);
		m_stackLayout->addWidget(list);
	}
	mainLayout->addLayout(m_stackLayout);
	connect(m_tab, &STabCtrl::tabSelected, this, &CreditDebtRanking::onTabSelected);
	connect(getData(), &CreditDebtRankingData::newDataArrived, this, &CreditDebtRanking::onDataArrived);
	loadData();
}

CreditDebtRankingList* CreditDebtRanking::CreateList(int index) {
	CreditDebtRankingData* data = getData();
	switch (index) {
	case emListActive: return new CreditDebtRankingActiveList(this, data);
	case emListRankingUp: return new CreditDebtRankingUpdownList(this, data, CreditDebtRankingUpdownList::emTypeUp);
	case emListRankingDown: return new CreditDebtRankingUpdownList(this, data, CreditDebtRankingUpdownList::emTypeDown);
	case emList20DaysFirst: return new CreditDebtRanking20DaysFirstList(this, data);
	default: return nullptr;
	}
}

CreditDebtRankingData* CreditDebtRanking::getData() const {
	return &FIDataCenter::instance().m_dataCreditDebtRanking;
}

void CreditDebtRanking::onDataArrived()
{
	auto* current = dynamic_cast<CreditDebtRankingList*>(m_stackLayout->currentWidget());
	if (current && current->isVisible()) {
		current->onReloadData();
	}
}

SDialog* CreditDebtRanking::clone(QWidget* parent)
{
	return new CreditDebtRanking(parent);
}

void CreditDebtRanking::onTabSelected(int index)
{
	m_stackLayout->setCurrentIndex(index);
	loadData();
}

void CreditDebtRanking::loadData() {
	getData()->loadData();
	onDataArrived();
}